package com.fzkj.juc.prodconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @DESCRIPTION 使用 lock 实现的生产者消费者模式
 */
public class ProdConsumer_V1_demo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.product();
            }
        }, "AAA").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.consumer();
            }
        }, "BBB").start();
    }

}

class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    // 生产者
    public void product() {
        lock.lock();
        try{
            // 如果不为0，生产者就等待
            while (number != 0){
                // 1、等待
                condition.await();
            }
            // 2、干活
            number++; // 这里要不要考虑多线程？
            System.out.println(this.number);
            // 3、通知唤醒
            condition.signalAll();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    // 消费者
    public void consumer() {
        lock.lock();
        try {
            while (number == 0){
                // 1、等待
                condition.await();
            }
            // 2、干活
            number--;
            System.out.println(this.number);
            // 3、通知
            condition.signalAll();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}
